//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.ee10.websocket.jakarta.common;

import java.util.concurrent.TimeUnit;

import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import org.eclipse.jetty.ee10.websocket.jakarta.common.sockets.TrackingSocket;
import org.eclipse.jetty.util.Callback;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;

public class JakartaWebSocketFrameHandlerOnOpenTest extends AbstractJakartaWebSocketFrameHandlerTest
{
    private void assertOnOpenInvocation(TrackingSocket socket, Matcher<String> eventMatcher) throws Exception
    {
        JakartaWebSocketFrameHandler localEndpoint = newJakartaFrameHandler(socket);

        // This invocation is the same for all tests
        localEndpoint.onOpen(coreSession, Callback.NOOP);
        String event = socket.events.poll(1, TimeUnit.SECONDS);
        assertThat("Event", event, eventMatcher);
    }

    @ClientEndpoint
    public static class OpenSocket extends TrackingSocket
    {
        @OnOpen
        public void onOpen()
        {
            addEvent("onOpen()");
        }
    }

    @Test
    public void testInvokeOpen() throws Exception
    {
        assertOnOpenInvocation(new OpenSocket(), containsString("onOpen()"));
    }

    @ClientEndpoint
    public static class OpenSessionSocket extends TrackingSocket
    {
        @OnOpen
        public void onOpen(Session session)
        {
            addEvent("onOpen(%s)", session);
        }
    }

    @Test
    public void testInvokeOpenSession() throws Exception
    {
        assertOnOpenInvocation(new OpenSessionSocket(),
            allOf(
                containsString("onOpen(oeje10wjc.JakartaWebSocketSession"),
                containsString(OpenSessionSocket.class.getName())
            ));
    }
}
